<template>
  <div style="width:300px;"
       class="left-tree-style">
    <div>
      <!-- 模糊查询  -->
      <el-input style="margin-bottom:10px;height:40px!important;line-height:40px!important;"
                placeholder="搜索分类"
                prefix-icon="el-icon-search"
                v-model="filterText"
                size="small"></el-input>
    </div>
    <p class="tips">温馨提示：树形可通过鼠标右键维护</p>
    <div style="height:400px;overflow-y:auto;">
      <el-tree class="treeShow"
               :data="treelist"
               :props="defaultProps"
               node-key="id"
               ref="SlotMenuList"
               :highlight-current="true"
               :filter-node-method="filterNode"
               @node-contextmenu="rihgtClick"
               @node-click="getId"
               :default-expanded-keys="idArr"
               draggable
               :accordion="false"
               :auto-expand-parent="false"
               :check-strictly="true">
        <span class="slot-t-node"
              slot-scope="{ node, data }">
          <!-- <span v-show="!node.isEdit"> -->
          <span>
            <!-- <span v-show="data.children && data.children.length >= 1"> -->
            <span v-show="data.children_list && data.children_list.length >= 1">
              <!-- <i :class="{'el-icon-time':node.level<=1,'el-icon-bell':node.level>1&&node.level<=2,'el-icon-service':node.level>2}" /> -->
              <i :class="{ 'el-icon-plus':!node.expanded,'el-icon-minus':node.expanded}" />
              <span :title="node.label"
                    id="show-ellipsis"
                    :class="[data.id >= maxexpandId ? 'slot-t-node--label' : '']">{{node.label}}</span>
            </span>
            <!-- 当树形节点不存在子节点时，设置单独的图标 -->
            <!-- <span v-show="!data.children|| data.children.length == 0"> -->
            <span v-show="!data.children_list|| data.children_list.length == 0">
              <i class="el-icon-document"></i>
              <span :title="node.label"
                    :class="[data.id >= maxexpandId ? 'slot-t-node--label' : '']">{{node.label}}</span>
            </span>
          </span>
        </span>
      </el-tree>
    </div>
    <!--鼠标右键点击出现页面-->
    <div v-show="menuVisible">
      <el-menu id="rightClickMenu"
               class="el-menu-vertical"
               @select="handleRightSelect"
               active-text-color="#fff"
               text-color="#fff">
        <!-- 根据不同的状态，显示不同的右键自定义菜单（岗位与非岗位状态） -->
        <el-menu-item index="1"
                      class="menuItem">
          <i class="el-icon-plus" />
          <span slot="title">新增</span>
        </el-menu-item>
        <el-menu-item index="2"
                      class="menuItem"
                      v-show="level>=2 ?true:false">
          <!-- && childNodes==0 -->
          <i class="el-icon-edit" />
          <span slot="title">修改</span>
        </el-menu-item>
        <el-menu-item index="3"
                      class="menuItem"
                      v-show="level>=2?true:false">
          <i class="el-icon-delete" />
          <span slot="title">删除</span>
        </el-menu-item>
        <el-menu-item index="4"
                      class="menuItem"
                      v-show="type=='code_tree'?false:true">
          <i class="el-icon-circle-plus-outline" />
          <span slot="title">新增子菜单</span>
        </el-menu-item>
        <el-menu-item index="5"
                      class="menuItem"
                      v-show="type=='code_tree'?false:true">
          <i class="el-icon-menu" />
          <span slot="title">新增部门</span>
        </el-menu-item>
        <el-menu-item index="6"
                      class="menuItem"
                      v-show="type=='code_tree'?false:true">
          <i class="el-icon-circle-check-outline" />
          <span slot="title">新增岗位</span>
        </el-menu-item>
      </el-menu>
    </div>
    <!-- 新增子单位 -->
    <el-dialog :visible.sync="addSonUnitDialog"
               :close-on-click-modal="false"
               width="30%">
      <el-form :model="sonUnitform"
               label-width="80px">
        <el-form-item label="单位编号">
          <el-input v-model="sonUnitform.num"
                    autocomplete="off"
                    style="width:80%"
                    placeholder="请输入单位编号"></el-input>
        </el-form-item>
        <el-form-item label="单位名称">
          <el-input v-model="sonUnitform.name"
                    autocomplete="off"
                    style="width:80%"
                    placeholder="请输入单位名称"></el-input>
        </el-form-item>
        <el-form-item label="单位类型">
          <el-select v-model="sonUnitform.type"
                     placeholder="请选择单位类型"
                     style="width:80%">
            <el-option label="区域一"
                       value="shanghai"></el-option>
            <el-option label="区域二"
                       value="beijing"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注"
                      class="add_tips">
          <el-input v-model="sonUnitform.tips"
                    autocomplete="off"
                    style="width:80%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="addSonUnitDialog=false">保 存</el-button>
        <el-button @click="addSonUnitDialog= false">返 回</el-button>
      </div>
    </el-dialog>
    <!-- 新增部门 -->
    <el-dialog :visible.sync="addDepDialog"
               :close-on-click-modal="false"
               width="30%">
      <el-form :model="departmentForm"
               label-width="80px">
        <el-form-item label="部门名称">
          <el-input v-model="departmentForm.name"
                    autocomplete="off"
                    placeholder="请输入部门名称"
                    style="width:80%"></el-input>
        </el-form-item>
        <el-form-item label="备注"
                      class="add_tips">
          <el-input v-model="departmentForm.tips"
                    autocomplete="off"
                    style="width:80%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="addDepDialog=false">保 存</el-button>
        <el-button @click="addDepDialog= false">返 回</el-button>
      </div>
    </el-dialog>
    <!-- 新增岗位 -->
    <el-dialog :visible.sync="addJobDialog"
               :close-on-click-modal="false"
               width="30%">
      <el-form :model="JobForm"
               label-width="80px">
        <el-form-item label="岗位名称">
          <el-input v-model="JobForm.name"
                    autocomplete="off"
                    placeholder="请输入岗位名称"
                    style="width:80%"></el-input>
        </el-form-item>
        <el-form-item label="备注"
                      class="add_tips">
          <el-input v-model="JobForm.tips"
                    autocomplete="off"
                    style="width:80%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="addJobDialog = false">保 存</el-button>
        <el-button @click="addJobDialog = false">返 回</el-button>
      </div>
    </el-dialog>
    <!-- 新增节点弹窗 -->
    <el-dialog :visible.sync="addNodeDialog"
               :close-on-click-modal="false"
               :before-close="handleClose"
               title="添加分类"
               width="30%">
      <el-form :model="addNodeForm"
               status-icon
               ref="addNodeForm"
               :rules="addNodeRules"
               label-width="80px">
        <el-form-item label="分类名称"
                      prop="name">
          <el-input v-model="addNodeForm.name"
                    autocomplete="off"
                    placeholder="请输入分类名称"
                    style="width:100%!important"></el-input>
        </el-form-item>
        <el-form-item label="分类编号"
                      class="add_tips"
                      prop="num">
          <el-input v-model="addNodeForm.num"
                    placeholder="请输入分类编号"
                    autocomplete="off"
                    style="width:100%!important"></el-input>
        </el-form-item>
      </el-form>
      <!-- <div slot="footer"
           class="dialog-footer"> -->
      <div style="text-align:center;">
        <el-button type="primary"
                   @click="addNodeDialog = false,addNodeForm.name='',addNodeForm.num=''"
                   id="save-style">返 回</el-button>
        <el-button @click="sureAddNode('addNodeForm')"
                   id="save-style"
                   style="color:white;">保 存</el-button>
      </div>
    </el-dialog>
    <!-- 修改节点弹窗 -->
    <el-dialog :visible.sync="editNodeDialog"
               :close-on-click-modal="false"
               title="修改分类"
               width="30%">
      <el-form :model="editNodeForm"
               status-icon
               ref="editNodeForm"
               :rules="editNodeRules"
               label-width="80px">
        <el-form-item label="分类名称"
                      prop="name">
          <el-input v-model="editNodeForm.name"
                    autocomplete="off"
                    placeholder="请输入分类名称"
                    style="width:100%!important"></el-input>
        </el-form-item>
        <el-form-item label="分类编号"
                      class="add_tips"
                      prop="num">
          <el-input v-model="editNodeForm.num"
                    placeholder="请输入分类编号"
                    disabled
                    autocomplete="off"
                    style="width:100%!important"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align:center;">
        <el-button type="primary"
                   @click="editNodeDialog = false"
                   id="save-style">返 回</el-button>
        <el-button @click="sureEditNode('editNodeForm')"
                   id="save-style"
                   style="color:white;">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ElCol from "element-ui/packages/col/src/col";
import { setInterval, clearInterval } from 'timers';
let id = 1000;
export default {
  name: 'leftTree',
  props: ["messageinfo", "treetype", "maxid", 'defaultId'],
  data () {
    var checkName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入分类名称'));
      } else if ((/^[\s　]|[ ]$/gi).test(value)) {
        callback(new Error('请输入正确的分类名称'));
      } else {
        callback();
      }
    };
    var checkNum = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入分类编号'));
      } else if ((/^[\s　]|[ ]$/gi).test(value)) {
        callback(new Error('请输入正确的分类编号'));
      } else {
        callback();
      }
    };
    var checkEditName = (rule, value, callback) => {
      callback();
    };
    var checkEditNum = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入分类编号'));
      } else if ((/^[\s　]|[ ]$/gi).test(value)) {
        callback(new Error('请输入正确的分类编号'));
      } else {
        callback();
      }
    };
    const item = {};
    return {
      info: this.messageinfo,
      treelist: [],
      type: this.treetype,
      idArr: this.defaultId,
      filterText: "",
      addSonUnitDialog: false,
      addDepDialog: false,//新增部门弹窗
      addJobDialog: false,//新增岗位弹窗
      addNodeDialog: false,//新增节点弹窗
      editNodeDialog: false,//修改节点弹窗
      DATA: null,
      NODE: null,
      maxexpandId: this.maxid, //新增节点开始id
      non_maxexpandId: this.maxid, //新增节点开始id(不更改)
      // maxexpandId: 95, //新增节点开始id
      // non_maxexpandId: 95, //新增节点开始id(不更改)
      isLoadingTree: true, //是否加载节点树
      level: 0,//右键点击节点的等级
      childNodes: [],
      defaultProps: {
        children: "children_list",
        label: "name"
      },
      menuVisible: false,
      objectID: null,
      // 子单位
      sonUnitform: {
        name: "",
        num: "",
        type: "",
        tips: ""
      },
      //部门
      departmentForm: {
        name: "",
        tips: ""
      },
      //岗位
      JobForm: {
        name: "",
        tips: ""
      },
      //分类（添加分类的弹窗表单）
      addNodeForm: {
        name: "",
        num: ""
      },
      addNodeRules: {
        name: [
          { validator: checkName, trigger: 'blur' }
        ],
        num: [
          { validator: checkNum, trigger: 'blur' }
        ],
      },
      //修改分类的弹窗表单
      editNodeForm: {
        name: "",
        num: ""
      },
      editNodeRules: {
        name: [
          { validator: checkEditName, trigger: 'blur' }
        ],
        num: [
          { validator: checkEditNum, trigger: 'blur' }
        ],
      },
      nodeData: {},
      nodeLevel: 0,
      editNodeData: {},
      editNodeLevel: 0
    };
  },
  methods: {
    //新增节点弹出框右上角关闭事件(清空记忆值)
    handleClose (done) {
      this.addNodeForm.name = '';
      this.addNodeForm.num = '';
      this.addNodeDialog = false;

    },
    //节点点击事件获取id
    getId (data, node, self) {
      data.level = node.level;
      this.menuVisible = false;
      this.$emit('getTreeNodeId', data);





      let curData = JSON.parse(JSON.stringify(data))
      //console.log('curData=', curData, node,data)
      //this.menuVisible = false

      if ((node.expanded || node.childNodes.length === 0) && data.id) {
        this.addNodeList(data.id)
      } else {
        this.removeNodeList(data.id)
      }
      //if (curData.object_no) {
      // if (this.selectedNodeList.indexOf(curData.object_id) < 0) {
      //   this.selectedNodeList.push(curData.object_id)
      // }
      //this.$emit('update:curPermissionNo', curData)
      //}
    },
    // 当当前节点是展开操作时,将当前节点的object_id添加到idArr中，为了刷新数据后能够展开到指定位置
    addNodeList (objectId) {
      // console.log('addNodeList=', objectId)
      let index = this.idArr.indexOf(objectId)
      if (index < 0) {
        this.idArr.push(objectId);
      }
    },
    // 当前节点是收起操作时，将当前节点的object_id从idArr中移除
    removeNodeList (objectId) {
      //console.log('removeNodeList=', objectId)
      let index = this.idArr.indexOf(objectId)
      if (index >= 0) {
        this.idArr.splice(index, 1)
      }
    },
    //对树节点进行筛选时执行的方法，返回 true 表示这个节点可以显示，返回 false 则表示这个节点会被隐藏
    filterNode (value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //右键弹出的菜单点击事件
    handleRightSelect (key) {
      if (key == 1) {
        this.NodeAdd(this.NODE, this.DATA);
        this.menuVisible = false; //关闭右键打开的操作菜单
      } else if (key == 2) {
        this.NodeEdit(this.NODE, this.DATA);
        this.menuVisible = false;
      } else if (key == 3) {
        this.NodeDel(this.NODE, this.DATA);
        this.menuVisible = false;
      } else if (key == 4) {
        this.menuVisible = false;
        this.addSonUnitDialog = true;
      } else if (key == 5) {
        this.menuVisible = false;
        this.addDepDialog = true;
      } else if (key == 6) {
        this.menuVisible = false;
        this.addJobDialog = true;
      }
    },
    NodeEdit (n, d) {
      //编辑节点
      if (d.code_type) {//判断修改的是标准码管理页面的树形还是参数管理的树形
        this.editNodeForm.num = d.code_type
      } else {
        this.editNodeForm.num = d.para_type
      }
      this.editNodeForm.name = d.name
      this.editNodeData = d
      this.editNodeLevel = n.level
      this.editNodeDialog = true
    },
    NodeDel (n, d) {
      //删除节点
      let that = this;
      if (d.children_list && d.children_list.length !== 0) {
        this.$message.error("此节点有子级，不可删除！");
        return false;
      } else {
        //新增节点可直接删除，已存在的节点要二次确认
        //删除操作
        let DelFun = () => {
          this.$emit('deleteTreeNode', d.id)
        };
        //二次确认
        let ConfirmFun = () => {
          this.$confirm("是否删除此节点？", "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              DelFun();
            })
            .catch(() => { });
        };
        //判断是否是新增节点
        d.id > this.non_maxexpandId ? DelFun() : ConfirmFun();
      }
    },
    NodeAdd (n, d) {
      //新增节点
      //判断层级
      if (n.level >= 4) {
        this.$message.error("最多只支持三级！");
        return false;
      }
      this.addNodeDialog = true
      this.nodeLevel = n.level
      this.nodeData = d
      //同时展开节点
      if (!n.expanded) {
        n.expanded = true;
      }
    },
    //新增节点弹窗确认按钮
    sureAddNode (addNodeForm) {
      this.$refs[addNodeForm].validate((valid) => {
        if (valid) {
          //console.log('保存=', addNodeForm);
          this.addNodeDialog = false
          var obj = {}
          obj.level = this.nodeLevel
          obj.id = this.nodeData.id
          obj.system_no = this.nodeData.system_no
          obj.p_code_type = this.nodeData.p_code_type
          obj.para_type = this.nodeData.para_type
          obj.name = this.addNodeForm.name
          obj.num = this.addNodeForm.num
          this.$emit('addTreeNode', obj)
          this.$refs[addNodeForm].resetFields();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //修改节点弹窗确认按钮
    sureEditNode (editNodeForm) {
      this.$refs[editNodeForm].validate((valid) => {
        if (valid) {
          this.editNodeDialog = false
          var obj = {}
          obj.level = this.editNodeLevel
          obj.id = this.editNodeData.id
          obj.system_no = this.editNodeData.system_no
          obj.p_code_type = this.editNodeData.p_code_type
          obj.p_para_type = this.editNodeData.p_para_type
          obj.name = this.editNodeForm.name
          obj.num = this.editNodeForm.num
          this.$emit('editTreeNode', obj)
          this.$refs[editNodeForm].resetFields();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //右键点击事件
    rihgtClick (event, object, value, element) {
      this.level = value.level
      this.childNodes = value.childNodes
      this.$emit('getTreeNodeValue', value)
      if (this.objectID !== object.id) {
        this.objectID = object.id;
        this.menuVisible = true;
        this.DATA = object;
        this.NODE = value;
      } else {
        this.menuVisible = !this.menuVisible;
        this.objectID = object.id;
        this.DATA = object;
        this.NODE = value;
      }
      document.addEventListener("click", e => {
        this.menuVisible = false;
      });
      let menu = document.querySelector("#rightClickMenu");
      let content = document.querySelector(".content-container")
      /* 菜单定位基于鼠标点击位置 */
      menu.style.left = event.clientX + 20 - 200 + "px";
      menu.style.top = event.clientY - 100 + content.scrollTop + "px";
      menu.style.position = "absolute"; // 为新创建的DIV指定绝对定位
      menu.style.width = 140 + "px";
    }
  },
  //监听值的改变
  watch: {
    filterText (val) {
      this.$refs.SlotMenuList.filter(val);
    },
    //监听父组件的值是否发生了修改，如果修改了就将新值覆盖旧值
    messageinfo (newValue, oldValue) {
      this.info = newValue;
      this.treelist = this.info
    },
    treetype (newValue, oldValue) {
      this.type = newValue;

    },
    maxid (newValue, oldValue) {
      this.maxexpandId = newValue;
      this.non_maxexpandId = newValue;
    },
    defaultId (newValue, oldValue) {
      this.idArr = newValue;
      //console.log('idArr=', this.idArr);
    }
  },
  created () {

  },
  mounted () {

  },
  updated () {

  }
};
</script>
<style lang="scss" scoped>
#save-style {
  background: rgba(26, 188, 156, 1);
}
/deep/ .left-tree-style .el-input__inner {
  padding-left: 30px;
  height: 40px !important;
  line-height: 40px !important;
}
/* 去掉默认的树形图标 */
/* .treeShow /deep/ .el-tree-node__content>.el-tree-node__expand-icon {
  display: none;
} */
.treeShow {
  margin-top: 10px !important;
}
.popover-new {
  /* position: absolute!important;
    right: 0;
    bottom: 0; */
}
/*顶部按钮*/
.slot-tree .slot-t-top {
  margin-bottom: 15px;
}
.slot-tree .slot-t-node span {
  display: inline-block;
}
/*节点*/
.slot-tree .slot-t-node--label {
  font-weight: 600;
}
/*输入框*/
.slot-tree .slot-t-input .el-input__inner {
  /* height: 26px;
		line-height: 26px; */
}
/*按钮列表*/
.slot-tree .slot-t-node .slot-t-icons {
  display: none;
  margin-left: 10px;
}
.slot-tree .slot-t-icons .el-button + .el-button {
  margin-left: 6px;
}
.slot-tree .el-tree-node__content:hover .slot-t-icons {
  display: inline-block;
}

/*************************标签鼠标右击页面样式******************************/
.el-menu-vertical {
  /* border: 3px solid rgb(84, 92, 100); */
  border: 2px solid #f5f7fa;
  border-radius: 10px;
  z-index: 100;
}
.el-menu-vertical i {
  color: #777777;
}
.menuItem {
  height: 40px;
  line-height: 40px;
  /* background-color: #545c64; */
  background-color: #f5f7fa;
  font-size: 14px;
}
/deep/ .menuItem i {
  color: #606266 !important;
}
/deep/ .menuItem span {
  color: #606266 !important;
}
.menuItem:hover {
  background-color: #409eff;
}
/deep/ .menuItem:hover i {
  color: #fff !important;
}

/deep/ .menuItem:hover span {
  color: #fff !important;
}
.add_tips /deep/ .el-form-item__label {
  /* padding-left: 28px; */
}
.tips {
  color: #9e9e9e;
  margin-bottom: 10px;
  text-align: center;
}
</style>